package com.mzy.linear_struct.ks.链表;


import java.util.HashMap;
import java.util.Map;

/**
 * @Author: mizy3
 * @Date: 2024/08/28/下午11:06
 * @Description:
 */
public class LRU缓存 {

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);
        LRUCache lruCache = new LRUCache(2);
        lruCache.put("a", 1);
        lruCache.put("a", 3);
        lruCache.put("b", 2);
        System.out.println(lruCache.get("a"));
        System.out.println(lruCache.get("b"));
        System.out.println(lruCache.get("a"));
        lruCache.put("c", 4);
        System.out.println(lruCache.get("c"));
        System.out.println(lruCache.get("b"));
        System.out.println(lruCache.get("a"));
    }
}

class LRUCache {
    static class Node {
        Node prev;
        Node next;
        String key;
        int val;

        public Node(String key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node head;
    public Node tail;
    public Map<String, Node> cache = new HashMap<>();
    public int capacity;
    public int size;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        head = new Node("-1", -1);
        tail = new Node("-1", -1);
        head.next = tail;
        tail.prev = head;
    }

    public void addHead(Node node) {
        Node next = head.next;
        next.prev = node;
        node.next = next;
        node.prev = head;
        head.next = node;
    }

    public Node removeLast() {
        Node last = tail.prev;
        last.prev.next = tail;
        tail.prev = last.prev;
        return last;
    }

    public Node remove(String key) {
        Node node = cache.get(key);
        Node prev = node.prev;
        Node next = node.next;
        prev.next = next;
        next.prev = prev;
        return node;
    }

    public void put(String key, int value) {
        Node node = new Node(key, value);
        // 判断是否是更新
        if (cache.containsKey(key)) {
            remove(key);
            addHead(node);
            cache.remove(key);
            cache.put(key, node);
        } else {
            // 添加
            // 判断是否容量已满
            if (size >= capacity) {
                // 满了，删除最后一个，添加最新的到head
                Node removed = removeLast();
                cache.remove(removed.key);
                addHead(node);
                cache.put(key, node);
            } else {
                addHead(node);
                cache.put(key, node);
                size++;
            }
        }
    }

    public int get(String key) {
        Node node = cache.get(key);
        if (node == null) return -1;

        remove(node.key);
        addHead(node);
        return node.val;
    }
}
